<template>
    <div>
     <!-- 头部 -->
     <van-nav-bar title="标题" left-arrow>
        <template #title>
              <van-field
                v-model="keyword"
                left-icon="search"
                placeholder="请输入关键词"
            />
        </template>
        <template #right>
            <span @click="searchFn">搜索</span>
        </template>
        </van-nav-bar>
          <!-- 历史记录 -->
          <div class="content">
              <h1>历史记录</h1>
              <ul>
                  <li @click="historySearch(item)" v-for="(item,index) in history" :key="index">{{item}}</li>
              </ul>
          </div>
          <!-- 搜索结果 -->
          <div class="content">
              <h1>搜索结果</h1>
              <ul>
                  <li @click="toPage(item.id)" v-for="item in result" :key="item.id" v-html="item.title">{{item.title}}</li>
              </ul>
          </div>
    </div>
</template>

<script>
import { post_search } from "@/api/news.js"
export default {
    data(){
        return {
            keyword: "",
            result: [],
            history: JSON.parse(localStorage.getItem("history-71"))||[]
        }
    },
    methods: {
        // 搜索
        searchFn(){
            // 历史记录，先判断历史记录中是否存在关键词，如果不存在则将关键词添加进历史记录中
            if(this.history.indexOf(this.keyword) == -1){
                this.history.push(this.keyword);
                localStorage.setItem("history-71", JSON.stringify(this.history) )
            }
            // 搜索
            post_search({
                keyword: this.keyword
            }).then(res=>{
                console.log(53,res);
                this.result = res.data.data;
                this.result.forEach(item=>{
                    item.title = item.title.replace(this.keyword, "<em style=color:red> "+this.keyword+" </em>" )
                })
            })
        },
        // 跳转到文章详情
        toPage(id){
            this.$router.push({
                path: "/articleDetail",
                query: {
                    id: id
                }
            })
        },
        // 点击历史记录搜索
        historySearch(val){
            this.keyword = val;
            this.searchFn();
        }
    }
}
</script>

<style lang="less" scoped>
/deep/.van-nav-bar {
        .van-cell{
        padding:  6px 16px;
    }
    .van-icon{
        color: #666 ;
    }
}
/deep/.van-field{
    border-radius: 20px;
    background-color: #eee;
    height: 36px;
    line-height: 36px;
    input{
        height: 24px;
    }
    .van-icon{
        color: #666     ;
        height: 24px;
    line-height: 24px;
    }
}
.content{
    padding: 0 5px;
    padding-bottom: 20px;
    border-bottom: 1px solid #666;
    h1{
        font-size: 25px;
        margin: 20px 0;
        font-weight: bold;
    }
    ul{
        li{
            font-size: 16px;
            line-height: 2;
        }
    }
}
</style>